import boto3
import sys
import time
import datetime


client = boto3.client('elbv2')


# shell

def deregister(tga, hostid, hostport):
    deregister_targets = client.deregister_targets(
        TargetGroupArn=tga,
        Targets=[
            {
                'Id': hostid,
                'Port': hostport,
            },
        ],
    )
    print(deregister_targets)

def getTargetHealth(tga, hostid, hostport):
    response = client.describe_target_health(
        TargetGroupArn=tga,
        Targets=[
            {
                'Id': hostid,
                'Port': hostport,
            },
        ],
    )

    health = response['TargetHealthDescriptions'][0]['TargetHealth']['State']
    return health


if __name__ == "__main__":

    # parameter

    tga = sys.argv[1]
    hostid = sys.argv[2]
    hostport = int(sys.argv[3])

    deregister(tga, hostid, hostport)

    health_status = getTargetHealth(tga, hostid, hostport)
    while health_status == 'healthy':
        time.sleep(1)
        health_status = getTargetHealth(tga, hostid, hostport)
        print("ELB切换完成，当前时间：{}，当前ELB使用状态：{}".format(datetime.datetime.now(), health_status))
    print("ELB切换完成，当前时间：{}，当前ELB使用状态：{}".format(datetime.datetime.now(), health_status))